package apptoko.com.view.quickpopup;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ScrollView;
import android.widget.Toast;
import apptoko.com.util.Utils;

import apptoko.com.R;
;

/**
 * QuickAction dialog, shows action list as icon and text like the one in
 * Gallery3D app. Currently supports vertical and horizontal layout.
 * 
 * @author Lorensius W. L. T <lorenz@londatiga.net>
 * 
 *         Contributors: - Kevin Peck <kevinwpeck@gmail.com>
 */
public class CustomQuickAction extends PopupWindows implements
		OnDismissListener {
	private View mRootView;
	private ImageView mArrowUp;
	private ImageView mArrowDown;
	private LayoutInflater mInflater;
	private ViewGroup mTrack;
	private ScrollView mScroller;
	private OnPopupDismissListener listener;
	private OnDismissListener mDismissListener;
	//private Session.StatusCallback statusCallback = new SessionStatusCallback();
	// private List<ActionItem> actionItems = new ArrayList<ActionItem>();

	private boolean mDidAction;

	//private int mChildPos;
	private int mInsertPos;
	private int mAnimStyle;
	private int mOrientation;
	private int rootWidth = 0;

	public static final int HORIZONTAL = 0;
	public static final int VERTICAL = 1;

	public static final int ANIM_GROW_FROM_LEFT = 1;
	public static final int ANIM_GROW_FROM_RIGHT = 2;
	public static final int ANIM_GROW_FROM_CENTER = 3;
	public static final int ANIM_REFLECT = 4;
	public static final int ANIM_AUTO = 5;

//	private Activity context;
//	private ProgressDialog pDialog;
//	String fbEmail = "";
//	String fbToken = "";
	/**
	 * Constructor for default vertical layout
	 * 
	 * @param context
	 *            Context
	 */
	public CustomQuickAction(Activity context) {
		this(context, VERTICAL);
		//this.context = context;
	}

	/**
	 * Constructor allowing orientation override
	 * 
	 * @param context
	 *            Context
	 * @param orientation
	 *            Layout orientation, can be vartical or horizontal
	 */
	public CustomQuickAction(Activity context, int orientation) {
		super(context);
		//this.context = context;
		mOrientation = orientation;

		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		if (mOrientation == HORIZONTAL) {
			setRootViewId(R.layout.popup_horizontal);
		} else {
			setRootViewId(R.layout.popup_vertical);
		}

		mAnimStyle = ANIM_AUTO;
		//mChildPos = 0;
	}

	/**
	 * Get action item at an index
	 * 
	 * @param index
	 *            Index of item (position from callback)
	 * 
	 * @return Action Item at the position
	 */
	// public ActionItem getActionItem(int index) {
	// return actionItems.get(index);
	// }

	/**
	 * Set root view.
	 * 
	 * @param id
	 *            Layout resource id
	 */
	public void setRootViewId(int id) {
		mRootView = (ViewGroup) mInflater.inflate(id, null);
		mTrack = (ViewGroup) mRootView.findViewById(R.id.tracks);

		mArrowDown = (ImageView) mRootView.findViewById(R.id.arrow_down);
		mArrowUp = (ImageView) mRootView.findViewById(R.id.arrow_up);

		mScroller = (ScrollView) mRootView.findViewById(R.id.scroller);

		// This was previously defined on show() method, moved here to prevent
		// force close that occured
		// when tapping fastly on a view to show quickaction dialog.
		// Thanx to zammbi (github.com/zammbi)
		mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));

		setContentView(mRootView);
	}

	/**
	 * Set animation style
	 * 
	 * @param mAnimStyle
	 *            animation style, default is set to ANIM_AUTO
	 */
	public void setAnimStyle(int mAnimStyle) {
		this.mAnimStyle = mAnimStyle;
	}

	/**
	 * Set listener for action item clicked.
	 * 
	 * @param listener
	 *            Listener
	 */
	// public void setOnActionItemClickListener(OnActionItemClickListener
	// listener) {
	// mItemClickListener = listener;
	// }

	public interface OnPopupDismissListener {
		public abstract void onDismissSuccess();

		public abstract void onDismissFail();
	}

	public void setPopupDismissListener(OnPopupDismissListener l) {
		this.listener = l;
	}

	/**
	 * Add action item
	 * 
	 * @param action
	 *            {@link ActionItem}
	 */
	public void addFrame(String type) {
		View container;
		if (type.equals("login")) {
			container = mInflater.inflate(R.layout.popup_login, null);
			final EditText editUsername = (EditText) container.findViewById(R.id.edit_username);
			final EditText editPassword = (EditText) container.findViewById(R.id.edit_password);
			Button btnLogin = (Button) container.findViewById(R.id.btn_login);
			//LoginButton btnLoginFB = (LoginButton) container.findViewById(R.id.btn_login_fb);
			//btnLoginFB.setReadPermissions(Arrays.asList("email", "read_stream","publish_stream", "read_friendlists"));
			btnLogin.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					String username = editUsername.getText().toString();
					String password = editPassword.getText().toString();
					if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
						Toast.makeText(activity, R.string.empty_field, Toast.LENGTH_SHORT).show();
						return;
					}
					String accessToken = Utils.getStaticAccessToken(activity);
//					LoginTask task = new LoginTask(activity);
//					task.setLoginListener(CustomQuickAction.this);
//					task.execute(accessToken, username, password);
				}
			});
//			btnLoginFB.setOnClickListener(new OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					// TODO Auto-generated method stub
//					Intent i = new Intent(activity, LoginActivity.class);
//					i.putExtra(DetailsActivity.IS_BROADCAST, 1);
//					activity.startActivity(i);
//					dismiss();
//				}
//			});
			mTrack.addView(container, mInsertPos);
		}
	}

	/**
	 * Show quickaction popup. Popup is automatically positioned, on top or
	 * bottom of anchor view.
	 * 
	 */
	public void show(View anchor) {
		preShow();

		int xPos, yPos, arrowPos;

		mDidAction = false;

		int[] location = new int[2];

		anchor.getLocationOnScreen(location);

		Rect anchorRect = new Rect(location[0], location[1], location[0]
				+ anchor.getWidth(), location[1] + anchor.getHeight());

		// mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
		// LayoutParams.WRAP_CONTENT));

		mRootView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

		int rootHeight = mRootView.getMeasuredHeight();

		if (rootWidth == 0) {
			rootWidth = mRootView.getMeasuredWidth();
		}

		int screenWidth = mWindowManager.getDefaultDisplay().getWidth();
		int screenHeight = mWindowManager.getDefaultDisplay().getHeight();

		// automatically get X coord of popup (top left)
		if ((anchorRect.left + rootWidth) > screenWidth) {
			xPos = anchorRect.left - (rootWidth - anchor.getWidth());
			xPos = (xPos < 0) ? 0 : xPos;

			arrowPos = anchorRect.centerX() - xPos;

		} else {
			if (anchor.getWidth() > rootWidth) {
				xPos = anchorRect.centerX() - (rootWidth / 2);
			} else {
				xPos = anchorRect.left;
			}

			arrowPos = anchorRect.centerX() - xPos;
		}

		int dyTop = anchorRect.top;
		int dyBottom = screenHeight - anchorRect.bottom;

		boolean onTop = (dyTop > dyBottom) ? true : false;

		if (onTop) {
			if (rootHeight > dyTop) {
				yPos = 15;
				LayoutParams l = mScroller.getLayoutParams();
				l.height = dyTop - anchor.getHeight();
			} else {
				yPos = anchorRect.top - rootHeight;
			}
		} else {
			yPos = anchorRect.bottom;

			if (rootHeight > dyBottom) {
				LayoutParams l = mScroller.getLayoutParams();
				l.height = dyBottom;
			}
		}

		showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up), arrowPos);

		setAnimationStyle(screenWidth, anchorRect.centerX(), onTop);

		mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos);
	}

	/**
	 * Set animation style
	 * 
	 * @param screenWidth
	 *            screen width
	 * @param requestedX
	 *            distance from left edge
	 * @param onTop
	 *            flag to indicate where the popup should be displayed. Set TRUE
	 *            if displayed on top of anchor view and vice versa
	 */
	private void setAnimationStyle(int screenWidth, int requestedX,
			boolean onTop) {
		int arrowPos = requestedX - mArrowUp.getMeasuredWidth() / 2;

		switch (mAnimStyle) {
		case ANIM_GROW_FROM_LEFT:
			mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left
					: R.style.Animations_PopDownMenu_Left);
			break;

		case ANIM_GROW_FROM_RIGHT:
			mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right
					: R.style.Animations_PopDownMenu_Right);
			break;

		case ANIM_GROW_FROM_CENTER:
			mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center
					: R.style.Animations_PopDownMenu_Center);
			break;

		case ANIM_REFLECT:
			mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Reflect
					: R.style.Animations_PopDownMenu_Reflect);
			break;

		case ANIM_AUTO:
			if (arrowPos <= screenWidth / 4) {
				mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left
						: R.style.Animations_PopDownMenu_Left);
			} else if (arrowPos > screenWidth / 4
					&& arrowPos < 3 * (screenWidth / 4)) {
				mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center
						: R.style.Animations_PopDownMenu_Center);
			} else {
				mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right
						: R.style.Animations_PopDownMenu_Right);
			}

			break;
		}
	}

	/**
	 * Show arrow
	 * 
	 * @param whichArrow
	 *            arrow type resource id
	 * @param requestedX
	 *            distance from left screen
	 */
	private void showArrow(int whichArrow, int requestedX) {
		final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp
				: mArrowDown;
		final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown
				: mArrowUp;

		final int arrowWidth = mArrowUp.getMeasuredWidth();

		showArrow.setVisibility(View.VISIBLE);

		ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams) showArrow
				.getLayoutParams();

		param.leftMargin = requestedX - arrowWidth / 2;

		hideArrow.setVisibility(View.INVISIBLE);
	}

	/**
	 * Set listener for window dismissed. This listener will only be fired if
	 * the quicakction dialog is dismissed by clicking outside the dialog or
	 * clicking on sticky item.
	 */
	public void setOnDismissListener(
			CustomQuickAction.OnDismissListener listener) {
		setOnDismissListener(this);

		mDismissListener = listener;
	}

	@Override
	public void onDismiss() {
		if (!mDidAction && mDismissListener != null) {
			mDismissListener.onDismiss();
		}
	}

	/**
	 * Listener for item click
	 * 
	 */
	public interface OnActionItemClickListener {
		public abstract void onItemClick(CustomQuickAction source, int pos,
				int actionId);
	}

	/**
	 * Listener for window dismiss
	 * 
	 */
	public interface OnDismissListener {
		public abstract void onDismiss();
	}

//	@Override
//	public void onLoginSuccess() {
//		// TODO Auto-generated method stub
//		listener.onDismissSuccess();
//		dismiss();
//	}
//
//	@Override
//	public void onLoginFail(AccessToken token) {
//		// TODO Auto-generated method stub
//		Toast.makeText(activity, token.getExpireDate(), Toast.LENGTH_SHORT).show();
//		listener.onDismissFail();
//	}

//	@Override
//	public void onLoginFBSuccess(AccessToken accessToken) {
//		// TODO Auto-generated method stub
//		((AppStoreVnApplication) context.getApplication()).setAccessToken(accessToken.getToken());
//		((AppStoreVnApplication) context.getApplication()).setLogin(true);
//		((AppStoreVnApplication) context.getApplication()).setLoginFaceBook(true);
//		listener.onDismissSuccess();
//		dismiss();
//	}
//
//	@Override
//	public void onLoginFBFail(int errorCode) {
//		// TODO Auto-generated method stub
//		((AppStoreVnApplication) context.getApplication()).setLogin(false);
//		((AppStoreVnApplication) context.getApplication()).setLoginFaceBook(false);
//		Toast.makeText(context, String.format(context.getResources().getString(R.string.login_fb_fail), errorCode), Toast.LENGTH_SHORT).show();
//		listener.onDismissFail();
//	}
//
//	@Override
//	public void onFBNotExist() {
//		// TODO Auto-generated method stub
//		AlertDialogManager am = new AlertDialogManager(context);
//		am.showButtonsDialog(R.string.fb_first_login, new DialogInterface.OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				// TODO Auto-generated method stub
//				switch (which) {
//				case DialogInterface.BUTTON_POSITIVE:
//					Intent register = new Intent(context, RegisterActivity.class);
//					register.putExtra(LoginActivity.FB_EMAIL, fbEmail);
//					register.putExtra(LoginActivity.FB_TOKEN, fbToken);
//					context.startActivity(register);
//					dismiss();
//					break;
//				case DialogInterface.BUTTON_NEGATIVE:
//					dialog.dismiss();
//					((AppStoreVnApplication) context.getApplication()).setLogin(false);
//					((AppStoreVnApplication) context.getApplication()).setLoginFaceBook(false);
//					dismiss();
//					break;
//				}
//			}
//		});
//	}
}